import React, { useEffect, useState } from 'react';
import { Icon } from 'antd';
import G6 from '@antv/g6';
import insertCss from 'insert-css';
import { Modal, Button } from 'antd';
import AddCategoryModal from '@/pages/KnowledgeGraph/edit/addCategoryModal';

const { confirm } = Modal;
let graph = null;

const KnowMap = props => {
  const { data, addCategory, editNode, delNode, fixSelectNode, zoom, sendGraph } = props;
  const ref = React.useRef(null);
  let visible = false;
  let selectNode = null;
  let item = null;
  let type = '';
  let addNodeType = '';
  insertCss(`
  #contextMenu {
    position: absolute;
    list-style-type: none;
    padding: 0;
    left: -150px;
    background-color: rgba(255, 255, 255,1);
    border: 1px solid #e2e2e2;
    border-radius: 4px;
    font-size: 12px;
    color: #545454;
  }
  #contextMenu li {
    cursor: pointer;
		list-style-type:none;
    list-style: none;
    margin-left: 0px;
    padding:10px;
    border:none;
    min-width:120px;
  }
  #contextMenu li:hover {
    color: #000;
    background: #d5f3fe;
  }
  #contextMenu li .icon{
    width: 16px;
    height: 16px;
    margin-right: 10px;
  }
  .reName{
   display:none;
  }
`);

  const COLLAPSE_ICON = function COLLAPSE_ICON(x, y, r) {
    return [
      ['M', x - r, y - r],
      ['a', r, r, 0, 1, 0, r * 2, 0],
      ['a', r, r, 0, 1, 0, -r * 2, 0],
      ['M', x + 2 - r, y - r],
      ['L', x + r - 2, y - r],
    ];
  };
  const EXPAND_ICON = function EXPAND_ICON(x, y, r) {
    return [
      ['M', x - r, y - r],
      ['a', r, r, 0, 1, 0, r * 2, 0],
      ['a', r, r, 0, 1, 0, -r * 2, 0],
      ['M', x + 2 - r, y - r],
      ['L', x + r - 2, y - r],
      ['M', x, y - 2 * r + 2],
      ['L', x, y - 2],
    ];
  };
  G6.registerEdge('line-arrow', {
    options: {
      style: {
        stroke: '#ccc',
      },
    },
    draw: function draw(cfg, group) {
      const startPoint = cfg.startPoint;
      const endPoint = cfg.endPoint;

      const stroke = (cfg.style && cfg.style.stroke) || this.options.style.stroke;
      const startArrow = (cfg.style && cfg.style.startArrow) || undefined;
      const endArrow = (cfg.style && cfg.style.endArrow) || undefined;

      const keyShape = group.addShape('path', {
        attrs: {
          path: [
            ['M', startPoint.x, startPoint.y],
            ['L', endPoint.x / 3 + (2 / 3) * startPoint.x, startPoint.y],
            ['L', endPoint.x / 3 + (2 / 3) * startPoint.x, endPoint.y],
            ['L', endPoint.x, endPoint.y],
          ],
          stroke,
          lineWidth: 1,
          startArrow,
          endArrow,
        },
        className: 'edge-shape',
        name: 'edge-shape',
      });
      return keyShape;
    },
  });

  G6.registerNode('tree-node', {
    drawShape: function drawShape(cfg, group) {
      let { nodeColor, name, textColor, childNumber, collapsed, nodeType, label } = cfg;
      if (name.length > 20) {
        name = name.substring(0, 19) + '...';
      }

      let rect = null;
      if (nodeType === 'flow') {
        rect = group.addShape('rect', {
          attrs: {
            fill: nodeColor,
            radius: 4,
            cursor: 'pointer',
          },
          name: 'title-box',
        });

        // left icon
        group.addShape('image', {
          attrs: {
            x: 8,
            y: 10,
            height: 20,
            width: 20,
            cursor: 'pointer',
            img: '../knowledge/knowMapImg/flow.png',
          },
          name: 'node-icon',
        });
        const content = name.replace(/(.{10})/g, '$1\n');
        let text = group.addShape('text', {
          attrs: {
            textBaseline: 'top',
            y: 10,
            x: 34,
            lineHeight: 20,
            text: content,
            fill: textColor,
            fontSize: 18,
            cursor: 'pointer',
          },
          name: 'title',
        });
        const bbox = text.getBBox();
        rect.attr({
          width: bbox.width + 40,
          height: bbox.height + 20,
        });
      } else {
        rect = group.addShape('rect', {
          attrs: {
            fill: nodeColor,
            radius: 4,
            cursor: 'pointer',
            x: 0,
            y: 0,
          },
          name: 'rect-shape',
        });

        const content = name.replace(/(.{10})/g, '$1\n');
        const text = group.addShape('text', {
          attrs: {
            text: content,
            textBaseline: 'top',
            fill: textColor,
            fontSize: 18,
            cursor: 'pointer',
            x: 14,
            y: 10,
          },
          name: 'rect-shape',
        });
        const bbox = text.getBBox();
        // const hasChildren = cfg.children && cfg.children.length > 0;
        const hasChildren = nodeType === 'root' || nodeType === 'category';
        if (hasChildren) {
          group.addShape('marker', {
            attrs: {
              x: bbox.maxX + 30,
              y: bbox.minX + bbox.height / 2,
              r: 6,
              symbol: cfg.collapsed ? EXPAND_ICON : COLLAPSE_ICON,
              stroke: '#fff',
              lineWidth: 2,
            },
            name: 'collapse-icon',
          });
        }
        rect.attr({
          width: bbox.width + (hasChildren ? 56 : 38),
          height: bbox.height + 20,
        });
      }

      return rect;
    },
  });

  useEffect(() => {
    if (!graph) {
      const conextMenuContainer = document.createElement('ul');
      conextMenuContainer.id = 'contextMenu';

      const addClassNodeLi = document.createElement('li');
      addClassNodeLi.setAttribute('class', 'addClassNode');

      const addClassIcon = document.createElement('img');
      addClassIcon.setAttribute('class', 'addNodeIcon icon');
      addClassIcon.setAttribute('src', '/knowMapImg/addChile.png');
      addClassNodeLi.appendChild(addClassIcon);
      const text = document.createElement('span');
      text.innerText = '新增类别节点';
      addClassNodeLi.appendChild(text);
      conextMenuContainer.appendChild(addClassNodeLi);

      const addTodoNodeLi = document.createElement('li');
      const addFlowIcon = document.createElement('img');
      addFlowIcon.setAttribute('class', 'addNodeIcon icon');
      addFlowIcon.setAttribute('src', '/knowMapImg/addClass.png');
      addTodoNodeLi.appendChild(addFlowIcon);
      const todoText = document.createElement('span');
      todoText.innerText = '新增意图节点';
      addTodoNodeLi.appendChild(todoText);
      addTodoNodeLi.setAttribute('class', 'addTodoNode');
      conextMenuContainer.appendChild(addTodoNodeLi);

      const editLi = document.createElement('li');
      const editIcon = document.createElement('img');
      editIcon.setAttribute('class', 'addNodeIcon icon');
      editIcon.setAttribute('src', '/knowMapImg/edit.png');
      editLi.appendChild(editIcon);
      const editText = document.createElement('span');
      editText.innerText = '编辑';
      editLi.appendChild(editText);
      editLi.setAttribute('class', 'editNode');
      conextMenuContainer.appendChild(editLi);

      const reNameLi = document.createElement('li');
      reNameLi.innerText = '节点重命名';
      reNameLi.setAttribute('class', 'reName');
      conextMenuContainer.appendChild(reNameLi);

      const delLi = document.createElement('li');
      delLi.setAttribute('class', 'delNodeBtn');
      const delIcon = document.createElement('img');
      delIcon.setAttribute('class', 'addNodeIcon icon');
      delIcon.setAttribute('src', '/knowMapImg/del.png');
      delLi.appendChild(delIcon);
      const delText = document.createElement('span');
      delText.innerText = '删除';
      delLi.appendChild(delText);
      conextMenuContainer.appendChild(delLi);

      document.getElementById('container').appendChild(conextMenuContainer);

      graph = new G6.TreeGraph({
        container: ref.current,
        width: ref.current.clientWidth,
        height: ref.current.clientHeight,
        modes: {
          default: [
            {
              type: 'collapse-expand',
              onChange: function onChange(item, collapsed) {
                const data = item.get('model');
                const icon = item
                  .get('group')
                  .find(element => element.get('name') === 'collapse-icon');
                if (collapsed) {
                  icon.attr('symbol', EXPAND_ICON);
                } else {
                  icon.attr('symbol', COLLAPSE_ICON);
                }
                data.collapsed = collapsed;
                return true;
              },
            },
            'drag-canvas',
            'zoom-canvas',
          ],
        },
        defaultNode: {
          type: 'tree-node',
          anchorPoints: [
            [0, 0.5],
            [1, 0.5],
          ],
        },
        defaultEdge: {
          // type: 'line-arrow',
          type: 'cubic-horizontal',
          style: {
            stroke: '#bcc6d0',
          },
        },
        layout: {
          type: 'compactBox',
          direction: 'LR',
          getId: function getId(d) {
            return d.id;
          },
          getHeight: function getHeight() {
            return 16;
          },
          getWidth: function getWidth() {
            return 180;
          },
          getVGap: function getVGap() {
            return 40;
          },
          getHGap: function getHGap() {
            return 40;
          },
        },
      });
      G6.Util.traverseTree(data, function(item) {
        item.nodeColor = fixColor(item.graphNodeType);
        item.textColor = fixTextColor(item.graphNodeType);
        item.childNumber = item.children ? item.children.length : 0;
        item.id = item.id ? item.id : item._id;
        item.name = item.title ? item.title : item.nodeName;
        item.nodeType = fixNodeType(item.graphNodeType);
        item.collapsed = handleNodeCollapsed(item);
      });

      /*
       * 节点收起判断
       * */
      function handleNodeCollapsed(node) {
        if (node.nodeType == 'category') {
          return true;
        }
      }

      graph.data(data);

      graph.render();
      graph.fitCenter();
      graph.on('canvas:contextmenu', evt => {
        evt.preventDefault();
        evt.stopPropagation();
      });
      graph.on('node:contextmenu', evt => {
        let { nodeType } = evt.item.getModel();
        evt.preventDefault();
        evt.stopPropagation();
        fixSelectNode(evt.item.getModel(), graph);
        if ((nodeType !== undefined && nodeType === 'intention') || nodeType === 'flow') {
          addClassNodeLi.style.display = 'none';
          addTodoNodeLi.style.display = 'none';
        } else {
          addClassNodeLi.style.display = 'block';
          addTodoNodeLi.style.display = 'block';
        }
        if (nodeType === 'root') {
          delLi.style.display = 'none';
        } else {
          delLi.style.display = 'block';
        }

        conextMenuContainer.style.left = `${evt.originalEvent.offsetX + 40}px`;
        conextMenuContainer.style.top = `${evt.originalEvent.offsetY}px`;
        selectNode = evt.item.getModel();
        item = evt.item;
      });

      addClassNodeLi.addEventListener('click', function() {
        addCategory(selectNode, 1, graph, '#3c817b', '#fff');
        conextMenuContainer.style.left = '-150px';
      });
      addTodoNodeLi.addEventListener('click', function() {
        addCategory(selectNode, 2, graph, '#fff', '#000');
        conextMenuContainer.style.left = '-150px';
      });
      delLi.addEventListener('click', function() {
        delNode(selectNode.id, graph);
        conextMenuContainer.style.left = '-150px';
      });
      reNameLi.addEventListener('click', function() {
        addCategory(item, 2, graph, '#fff', '#000', selectNode.name);
        conextMenuContainer.style.left = '-150px';
      });
      editLi.addEventListener('click', function() {
        editNode(item, 2, graph, '#fff', '#000', selectNode.name);
        conextMenuContainer.style.left = '-150px';
      });

      graph.on('node:mouseleave', () => {
        // conextMenuContainer.style.left = '-150px';
      });
      graph.on('node:click', e => {
        e.preventDefault();
        e.stopPropagation();
        fixSelectNode(e.item.getModel(), graph);
        if (e.item.getModel().nodeType === 'intention' || e.item.getModel().nodeType === 'flow') {
          editNode(e.item, 2, graph, '#fff', '#000', e.item.getModel().name);
        }
      });
      graph.on('wheelzoom', e => {
        zoom(parseInt(graph.getZoom() * 100), graph);
      });
      graph.on('canvas:click', e => {
        conextMenuContainer.style.left = '-150px';
        sendGraph(graph);
      });
      graph.on('canvas:mouseenter', e => {
        sendGraph(graph);
      });
    }
  }, []);
  function fixColor(nodeType) {
    if (nodeType === 0) {
      return '#318ff7';
    }
    if (nodeType === 1) {
      return '#f0b663';
    }
    return '#dce8f3';
  }
  function fixTextColor(nodeType) {
    if (nodeType === 0 || nodeType === 1) {
      return '#fff';
    }
    return '#318ff7';
  }

  function fixNodeType(nodeType) {
    if (nodeType === 0) {
      return 'root';
    }
    if (nodeType === 1) {
      return 'category';
    }
    if (nodeType === 2) {
      return 'intention';
    }
    return 'flow';
  }

  return (
    <div>
      <div
        ref={ref}
        id="container"
        style={{ height: 'calc(80vh)', width: '100%', overflow: 'hidden' }}
      />
    </div>
  );
};

export default KnowMap;
